package com.probiz.estore.cart.service.dwr;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.probiz.estore.Constants;
import com.probiz.estore.cart.util.ShoppingCartUtil;
import com.probiz.estore.common.model.cart.Shoppingcart;
import com.probiz.estore.common.model.cart.ShoppingcartItem;
import com.probiz.estore.common.model.customer.Address;
import com.probiz.estore.common.model.order.CheckoutSession;
import com.probiz.estore.common.model.order.SalesOrder;
import com.probiz.estore.common.model.product.ProductSku;
import com.probiz.estore.common.model.system.SelfCollectionCentre;
import com.probiz.estore.common.model.system.ShippingRate;
import com.probiz.estore.common.service.CheckoutService;
import com.probiz.estore.common.service.CustomerService;
import com.probiz.estore.common.service.GiftCertificateService;
import com.probiz.estore.common.service.ProductService;
import com.probiz.estore.exception.CheckoutException;
import com.probiz.estore.exception.GiftCertificateStateException;
import com.probiz.estore.exception.OutOfStockException;
import com.probiz.estore.exception.ShopPointConsumptionException;
import com.probiz.estore.webapp.util.RequestContext;

/**
 * Checkout 前台服务类
 * @author huangwm210
 *
 */
public class CheckoutDwr {

	private CustomerService customerService;
    private CheckoutService checkoutService;
    private ProductService productService;
	private GiftCertificateService giftCertificateService;
	
	public void setCheckoutService(CheckoutService checkoutService) {
		this.checkoutService = checkoutService;
	}

	public String getConsigneeData(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getConsigneeData());
		return json.toString();
	}
	
	public String saveConsigneeData(HttpServletRequest request,HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setConsigneeData(json);
		return "true";
	}
	
	public String getVirtualConsigneeData(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getVirtualConsigneeData());
		return json.toString();
	}
	
	public String saveVirtualConsigneeData(HttpServletRequest request,HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setVirtualConsigneeData(json);
		return "true";
	}
	
	public String applyFavoriteAddress(HttpServletRequest request,HttpServletResponse response, Integer index) {
		if (!RequestContext.isAnonymousUser()) {
			List<Address> addressList = customerService.getAllShippingAddressByAppuserId(RequestContext.getCurrentUserId());
			Address selectedAddress = addressList.get(index);
			CheckoutSession.getCurrentSession().applyAddress(selectedAddress);
		}
		
		return "true";
	}
	
	
	public String getPaymentMethodData(HttpServletRequest request, HttpServletResponse response){	
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getPaymentMethodData());
		return json.toString();
	}
	
	public String savePaymentMethodData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		if(RequestContext.isStoreFront()){
			checkoutSession.setPaymentMethodData(json);
		}else if(RequestContext.isMobileFront()){
			checkoutSession.setPaymentMethodData4MobileFront(json);
		}
		return "true";
	}
	
	public String getShippingMethodData(HttpServletRequest request, HttpServletResponse response){	
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getShippingMethodData());
		return json.toString();
	}
	
	public String saveShippingMethodData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setShippingMethodData4MobileFront(json);
		return "true";
	}
	
	public String getRemarkData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getRemarkData());
		return json.toString();
	}
	
	public String saveRemarkData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setRemarkData(json);
		return "true";
	}
	
	public String getInvoiceData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getInvoiceData());
		return json.toString();
	}
	
	public String saveInvoiceData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setInvoiceData(json);
		return "true";
	}
	
	public String getGiftWrapData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getGiftWrapData());
		return json.toString();
	}
	
	public String saveGiftWrapData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setGiftWrapData(json);
		return "true";
	}
	
	public String getGiftCertificatePaymentData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getGiftCertificatePaymentData());
		return json.toString();
	}
	
	public String saveGiftCertificatePaymnentData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		JSONObject result = new JSONObject();
		String giftCertificateNo = json.getString("giftCertificateNo");
		try {
			giftCertificateService.checkGiftcertificate(giftCertificateNo);
		} catch (GiftCertificateStateException e) {
			result.put("error", e.getMessage());  
			return result.toString();
		}

		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setGiftCertificatePaymentData(json);
		return "true";
	}
	
	//删掉一个礼品券
	public String removeGiftCertificate(HttpServletRequest request, HttpServletResponse response, String giftCertificateNo) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.removeGiftCertificate(giftCertificateNo);
		return "true";
	}
	
	public String getShopPointPaymentData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getShopPointPaymentData());
		return json.toString();
	}
	
	public String saveShopPointPaymentData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		JSONObject result = new JSONObject();
		result.putAll(CheckoutSession.getCurrentSession().setShopPointPaymentData(json));
		return result.toString();
	}
	
	public String getBillData(HttpServletRequest request, HttpServletResponse response){
		JSONObject json = new JSONObject();
		json.putAll(CheckoutSession.getCurrentSession().getBillData4Preview());
		return json.toString();
	}
	
	public String saveAllData(HttpServletRequest request, HttpServletResponse response, JSONObject json) {
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		checkoutSession.setConsigneeData(json);
		checkoutSession.setPaymentMethodData(json);
		checkoutSession.setRemarkData(json);
		checkoutSession.setInvoiceData(json);
		checkoutSession.setGiftWrapData(json);
		return "true";
	}
	
	/**
	 * 取得能送达指定配送地址的运输方式列表
	 * @param request
	 * @param response
	 * @param strRegionId	如果为空即从session中去取
	 * @return
	 */
	public String retrieveShippingMethodList(HttpServletRequest request, HttpServletResponse response,
			String strRegionId, String strIsCod) {
		JSONArray array = new JSONArray();
		List<ShippingRate> shippingRateList;
		Integer regionId = null;
		Boolean isCod = null;
		try {
			regionId = Integer.valueOf(strRegionId);
			isCod = Boolean.valueOf(strIsCod);
		} catch (NumberFormatException e) {
			//DO NOTHING
		}
		
		if (regionId == null || isCod == null) {
			shippingRateList = CheckoutSession.getCurrentSession().getShippingRateList();
		} else {
			shippingRateList = checkoutService.getRegionShippingRates(isCod, regionId);
		}
		
		for (ShippingRate shippingRate : shippingRateList) {
			JSONObject json = new JSONObject();
			json.put("shippingRateId", shippingRate.getShippingRateId());
			json.put("shippingMethodName", shippingRate.getShippingMethod().getShippingMethodName());
			if (shippingRate.getShippingMethod().getShippingCost() != null) {
				json.put("shippingCost", shippingRate.getShippingMethod().getShippingCost().toString());
			}
			json.put("estimatedDeliveryTime", shippingRate.getShippingMethod().getDeliveryTime());
			json.put("supportSpecifyingDeliveryTime", shippingRate.getShippingMethod().getSupportSpecifyingDeliveryTime() == 1);
			json.put("shippingMethodDetail", shippingRate.getShippingMethod().getShippingMethodDetail());
			array.add(json);
		}

		return array.toString();
	}
	
	/**
	 * 取得客户所在地区的提货中心列表数据
	 * @param request
	 * @param response
	 * @return
	 */
	public String retrieveSelfCollectionCentreList(HttpServletRequest request, HttpServletResponse response, 
			String regionId) {
		JSONArray array = new JSONArray();
		List<SelfCollectionCentre> selfCollectionCentreList;
		if (StringUtils.isNotBlank(regionId)) {
			selfCollectionCentreList = checkoutService.getSelfCollectionCentreListByRegionId(Integer.valueOf(regionId));
		} else {
			selfCollectionCentreList = CheckoutSession.getCurrentSession().getSelfCollectionCentreList();
		}
		
		for (SelfCollectionCentre selfCollectionCentre : selfCollectionCentreList) {
			JSONObject json = new JSONObject();
			json.put("selfCollectionCentreId", selfCollectionCentre.getSelfCollectionCentreId());
			json.put("selfCollectionCentreName", selfCollectionCentre.getSelfCollectionCentreName());
			json.put("address", selfCollectionCentre.getAddress());
			array.add(json);
		}

		return array.toString();
	}
	
	//下订单
	public String placeOrder(HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		
		boolean exceptionOccured = false;
		
		if (request.getSession().getAttribute("checkoutSession") == null) {
			exceptionOccured = true;
			result.put("error", "登录超时");
			return result.toString();
		}
		
		try {
			SalesOrder salesOrder = checkoutService.doPlaceOrder(CheckoutSession.getCurrentSession());
			ShoppingCartUtil.getInstance().updateShoppingcartCookie(null, response);
			result.put("orderNo", salesOrder.getOrderNo());
		} catch (OutOfStockException e) {
			exceptionOccured = true;
			result.put("error", e.getMessage());
		} catch (GiftCertificateStateException e) {
			exceptionOccured = true;
			result.put("error", e.getMessage()); 
		} catch (ShopPointConsumptionException e) {
			exceptionOccured = true;
			result.put("error", e.getMessage()); 
		} catch (CheckoutException e) {
			exceptionOccured = true;
			result.put("error", e.getMessage()); 
			result.put("exceptionType", e.getType()); 
		}catch (RuntimeException e) {
			exceptionOccured = true;
			result.put("error", e.getMessage());
			e.printStackTrace();
		} 
		
		if (exceptionOccured) {
			//结帐异常后session里的productSku对像与hibernate上下文脱离，此时页面上再显示商品信息(例如orderSkuOptionValue)会出错。
			Shoppingcart shoppingcart = CheckoutSession.getCurrentSession().getShoppingcart();
			for (ShoppingcartItem shoppingcartItem: shoppingcart.getProductItems()) {
				ProductSku productSku = productService.getProductSkuPojoByProductSkuCode(shoppingcartItem.getProductSku().getProductSkuCode());
				shoppingcartItem.setProductSku(productSku);
			}
		}
		
		return result.toString();
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	
	public void setGiftCertificateService(GiftCertificateService giftCertificateService) {
		this.giftCertificateService = giftCertificateService;
	}
	
	public void setCustomerId(HttpServletRequest request,HttpServletResponse response, Integer customerId) {
		//禁止前台调用该方法
		CheckoutSession checkoutSession = CheckoutSession.getCurrentSession();
		if (customerId != null && checkoutSession != null && checkoutSession.getShoppingcart() != null) {
			checkoutSession.getShoppingcart().setCustomerId(customerId);
		}
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}
	
}
